<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\AliPayAppController;
use App\Http\Controllers\AliPayController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\PlaceController;
use App\Http\Controllers\SmsController;
use App\Http\Controllers\WechatController;
use App\Models\BrowseJob;
use App\Models\CollArea;
use App\Models\CollPosition;
use App\Models\CompanyBasic;
use App\Models\CompanyJob;
use App\Models\CompanyUser;
use App\Models\Interview;
use App\Models\PersonalUser;
use App\Models\ProductsInvoice;
use App\Models\Resume;
use App\Models\ResumeSend;
use App\Models\WebConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Validator, DB;

class InvoiceController extends CommonController
{
    /**
     * 所有职位
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $totalList = 10;
        $page = $request->page;
        $start = ($page - 1) * $totalList;
        $type = $request->type;

//        return response()->json(['status' => 0, 'msg' => $request->lat]);

        $company_job = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            //获取字段
            ->select(
                't1.id', 't1.job_title', 't1.job_category1', 't1.location1', 't1.address', 't1.salary', 't1.description', 't1.welfare', 't1.updatetime', 't1.ip_id',
                't2.company_name', 't2.logo'
            )
            ->where('job_status', 1)
            //本公司招聘除外
            ->where(function ($query) use ($request) {
                $user = auth()->guard('company')->user();
                if ($user && $user->uid > 0) {
                    $query->where('t1.uid', '!=', $user->uid);
                }
            })
            //薪资
            ->where(function ($query) use ($request) {
                if (!empty($request->salary)) {
                    $salarys = WebConfig::getConfig('salary');

                    if ($salarys) {
                        $salarys1 = explode(',', $salarys);
                        foreach ($salarys1 as $v111) {
                            $arr = explode(':', $v111);
                            if ($arr[0] != $request->salary) {
                                continue;
                            }
                            $salarysStr = $arr[1];
                            $salarysArr = explode('-', $salarysStr);
                            if ($salarysArr) {
                                $minSalary = $salarysArr[0];
                                $maxSalary = $salarysArr[1];

                                if ($maxSalary > $minSalary) {
                                    $query->where('t1.salary', '>=', $minSalary)
                                        ->where('t1.salary', '<', $maxSalary);
                                }
                            }

                        }
                    }
                }
            })
            //工作地点
            ->where(function ($query) use ($request) {
                $location1 = $request->input('district');

                if ($location1 > 0) {
                    $query->where('t1.location1', '=', $location1);
                }
            })
            //所属行业
            ->where(function ($query) use ($request) {
                $job_category1 = $request->input('jobsort');

                if ($job_category1 > 0) {
                    $query->where('t1.job_category1', '=', $job_category1);
                }
            })
            //关键字
            ->where(function ($query) use ($request) {
                if (!empty($request->keyword)) {
                    $query->where('t1.job_title', 'like', '%' . $request->keyword . '%')
                        ->orWhere('t2.company_name', 'like', '%' . $request->keyword . '%');
                }
            })
            ->orderBy('id', 'desc')
            ->get()->toArray();

        $lat = $request->lat;
        $lng = $request->lng;

        if (count($company_job) > 0) {
            $farNear = WebConfig::getConfig('far_nearby');

            foreach ($company_job as $k => $v) {
                //地区
                $v->location = CollArea::getAreaName($v->location1);

                if (trim($v->location) == '') {
                    $v->location = "地区不限";
                }
                if ($v->address) {
                    $v->location = $v->location . ' ' . $v->address;
                }

                $v->job_category1 = CollPosition::getPosName($v->job_category1);

                if ($type == 2 && $lat > 0 && $lng > 0 && $v->ip_id > 0) {
                    $latlng = DB::table('latlng_info')->where('id', $v->ip_id)->value('auto_navi');
                    $latlngArr = explode(',', $latlng);

                    $v->distance = $this->getDistance($lat, $lng, $latlngArr[1], $latlngArr[0]);
                    if ($v->distance > $farNear) {
                        unset($company_job[$k]);
                        continue;
                    }
                    $v->distance = round($v->distance, 2);
                } else {
                    $v->distance = 0;
                }

                $v->is_new = 0;
            }

            $company_job_arr = $this->object_to_array($company_job);

            if ($type == 2 && $lat > 0 && $lng > 0) {
                $distances = array_column($company_job_arr, 'distance');
                array_multisort($distances, SORT_ASC, $company_job_arr);
            }

            $company_job_arr = array_slice($company_job_arr, $start, $totalList);
        } else {
            $company_job_arr = [];
        }

        return response()->json(['status' => 1, 'data' => $company_job_arr]);
    }

    /**
     * 添加发票
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addInvoice(Request $request)
    {
        $invoiceType = $request->invoice_type;
        $type = $request->type;
        if ($invoiceType == 2 && $type == 1) {
            return response()->json(['status' => 0, 'msg' => '专用发票仅限企业使用！']);
        }
        $input = $request->input();
        if ($type == 1) {
            $rules = [
                'title' => 'required',
            ];
            $messages = [
                'title.required' => '发票抬头必填'
            ];
        } elseif ($type == 2) {
            $rules = [
                'title' => 'required',
                'regist_number' => 'required',
                'address' => 'required',
                'mobile' => 'required',
                'bankname' => 'required',
                'banknumber' => 'required',
            ];
            $messages = [
                'title.required' => '发票抬头必填',
                'regist_number.required' => '纳税人识别号必填',
                'address.required' => '地址必填',
                'mobile.required' => '电话必填',
                'bankname.required' => '银行卡名称必填',
                'banknumber.required' => '银行卡号必填',
            ];
        }

        $validate = Validator::make($input, $rules, $messages);
        if ($error = $validate->errors()->first()) {
            return response()->json(['status' => 0, 'msg' => $error]);
        }

        $status = $input['status'];
        $uid = $input['uid'];
        if ($status == 1) {
            ProductsInvoice::where('uid', $uid)->update(['status' => 0]);
        }
        unset($input['token']);
        $res = ProductsInvoice::create($input);
        if ($res->id > 0) {
            return response()->json(['status' => 1, 'msg' => '添加成功！', 'data' => $res->id]);
        } else {
            return response()->json(['status' => 0, 'msg' => '添加失败']);
        }
    }

    /**
     * 删除发票
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delInvoice(Request $request)
    {
        $id = $request->id;
        $uid = $request->uid;
        if (!$id) {
            return response()->json(['status' => 0, 'msg' => '参数缺失！']);
        }

        $invoiceInfo = ProductsInvoice::where('uid', $uid)->where('id', $id)->first();
        if (!$invoiceInfo) {
            return response()->json(['status' => 0, 'msg' => '该发票不存在！']);
        }

        $res = ProductsInvoice::destroy($id);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '删除成功！']);
        } else {
            return response()->json(['status' => 0, 'msg' => '删除失败']);
        }
    }
}
